<?php


namespace app\zyhsapi\model;


use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use think\Log;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsAppleidUser extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_appleid_user';
    protected $cacheModel = 'user.apple';

    public function SaveData($data)
    {
        $res = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $data['apple_id'] . ':register')->setCacheType('string')->getCache();
        if ($res)
        {
            throw new ApiException('当前账号已注册，请勿重复操作');
        }
        CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $data['apple_id'] . ':register')->setCacheType('string')->setCacheTime(2)->setCache('1');
        try
        {
            $chennelId = Util::getChannelId();
            $data['channel_id'] = $chennelId;
            $this->allowField(true)->isUpdate(false)->save($data);
        }
        catch (\Exception $e)
        {
            Log::write('添加用户apple信息失败：' . $e->getMessage(), 'error', true);
            return false;
        }
        return true;
    }

    /**
     * 更新apple信息
     * @param $data
     * @param $map
     * @param string $appleId
     * @return bool
     * @throws \Exception
     */
    public function UpdateData($data, $map, string $appleId)
    {
        try
        {
            $this->where($map)->update($data);
        }
        catch (\Exception $e)
        {
            return false;
        }
        CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $appleId)->rmCache();
        return true;
    }

    /**
     * 解绑数据
     * @param int $uid
     * @return bool
     * @throws \Exception
     */
    public function delData(int $uid)
    {
        $apple_id = $this->getAppleId($uid);
        try
        {
            $this->where('uid', $uid)->delete();
        }
        catch (\Exception $e)
        {
            return false;
        }

        if ($apple_id)
        {
            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('uid_bind_appleid', $uid)->rmCache('uid_bind_appleid');
            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $apple_id)->rmCache();
        }
        return true;
    }

    /**
     * 缓存获取用户Apple信息
     * @param string $appleId
     * @return array|bool|mixed
     * @throws ApiException
     */
    public function getUserInfo(string $appleId)
    {
        $data = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $appleId)->getDataAndSet(function () use ($appleId)
        {
            return $this->getAppleInfoFromDms($appleId);
        });

        if ($data && $data['forbidden'] == 1)
        {
            throw new ApiException('该账号禁止登录', 200, 0);
        }
        return $data;
    }

    /**
     * 数据库获取用户Apple信息
     * @param string $appleId
     * @return array|mixed
     */
    public function getAppleInfoFromDms(string $appleId)
    {
        try
        {
            $data = $this->alias('a')->join('good_wechat.zyhs_user u', 'a.uid=u.id')
                ->where('apple_id', $appleId)->column('a.uid,a.nickname,a.email,a.create_time,u.forbidden,u.has_self_recode,u.avatar');
            $data = current($data);
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    /**
     * 通过uid取绑定苹果ID
     * @param $uid
     * @return string
     * @throws \Exception
     */
    public function getAppleId($uid)
    {
        $appleId = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheType('string')
            ->setCacheKeyDetail('uid_bind_appleid', $uid)->getDataAndSet(function () use ($uid)
            {
                try
                {
                    $apple_id = $this->where('uid', $uid)->value('apple_id');

                    if ($apple_id)
                    {
                        return $apple_id;
                    } else
                    {
                        return '1';
                    }
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    return '1';
                }
            }, [], 'uid_bind_appleid');

        return $appleId && $appleId !== '1' ? $appleId : '';
    }

    public function rmHasBindAppleid($uid)
    {
        CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('uid_bind_appleid', $uid)->rmCache('uid_bind_appleid');
    }
}
